<template>
  <div class="user-information">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>基本资料</span>
        </div>
      </template>
      <el-form
        :label-position="labelPosition"
        label-width="100px"
        :model="formData"
        :rules="rules"
        ref="formRef"
        style="max-width: 460px"
      >
        <el-form-item label="登录名称：">
          <el-input v-model="formData.username" disabled />
        </el-form-item>
        <el-form-item label="用户昵称：" prop="nickname">
          <el-input v-model="formData.nickname" />
        </el-form-item>
        <el-form-item label="用户邮箱：" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)"
            >提交修改</el-button
          >
          <el-button @click="resetForm(formRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import store from '../store'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import { updateUserinfoRequest } from '../api/user.js'

const labelPosition = ref('right')
const formRef = ref()
const formData = computed(() => {
  return store.state.userinfo
})
// const formData = reactive({
//   username: userinfo.value.username,
//   nickname: userinfo.value.nickname,
//   email: userinfo.value.email,
// })
const rules = reactive({
  nickname: [
    {
      required: true,
      message: '昵称不能为空!',
      trigger: 'blur',
    },
  ],
  email: [
    {
      required: true,
      message: '邮箱不能为空!',
      trigger: 'blur',
    },
  ],
})

// 提交修改
const submitForm = async (formRef) => {
  if (!formRef) return
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      const params = qs.stringify({
        id: formData.value.id,
        nickname: formData.value.nickname,
        email: formData.value.email,
      })
      const { data: res } = await updateUserinfoRequest(params)
      // console.log(res)
      const { status, message } = res
      if (status !== 0) ElMessage.error(message)
      ElMessage.success(message)
    } else {
      ElMessage.error('校验失败!')
    }
  })
}

// 重置
const resetForm = (formRef) => {
  if (!formRef) return
  formRef.resetFields()
}
</script>
